package main

import (
	"fmt"
	"gorm.io/gorm"
	"time"
)

type UserModel struct {
	ID       uint
	Name     string
	Collects []ArticleModel `gorm:"many2many:user_collect_models;joinForeignKey:UserID;JoinReferences:ArticleID"`
}
type ArticleModel struct {
	ID    uint   `gorm:"type:uint"`
	Title string `gorm:"type:varchar(30)"`
}
type UserCollectModel struct {
	ArticleID    uint         `gorm:"primaryKey"`
	ArticleModel ArticleModel `gorm:"foreignKey:ArticleID"`
	UserModel    UserModel    `gorm:"foreignKey:UserID"`
	UserID       uint         `gorm:"primaryKey"`
	CreatedAt    time.Time    `json:"created_at"`
}

func main() {
	//DB.SetupJoinTable(&UserModel{}, "Collects", &UserCollectModel{}) //自定义连接表 通过Article表查设置tag\
	//DB.AutoMigrate(&ArticleModel{}, &UserModel{}, &UserCollectModel{})
	DB = DB.Session(&gorm.Session{
		Logger: mysqlLogger,
	})
	//根据用户查询收藏的文章列表
	//var user UserModel
	//DB.Preload("Collects").Take(&user, "name=?", "wxd")
	//fmt.Println(user)
	//var collects []ArticleModel
	//DB.Model(&user).Limit(1).Association("Collects").Find(&collects)
	//fmt.Println(collects)
	//直接查询连接表
	var UserCollects []UserCollectModel
	DB.Preload("ArticleModel").Preload("UserModel").Find(&UserCollects, 1)
	fmt.Println(UserCollects)

}
